package com.zy.servlet.user;

import com.google.gson.Gson;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.zy.entity.User;
import com.zy.service.GetUserService;
import com.zy.service.impl.GetUserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

/**
 * 获取用户列表的Servlet
 */
@WebServlet("/getUsers")
public class GetUserServlet extends HttpServlet {
    private GetUserService getUserService = new GetUserServiceImpl();
    private Gson gson = new Gson();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        try {
            // 获取所有用户
            List<User> users = getUserService.getAllUsers();
            // 转换为JSON并返回
            String json = gson.toJson(users);
            response.getWriter().write(json);
        } catch (Exception e) {
            // 打印异常栈信息
            e.printStackTrace();
            // 设置响应状态为内部服务器错误
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            // 将错误信息转换为JSON并返回
            response.getWriter().write(gson.toJson("获取用户列表失败：" + e.getMessage()));
        }
    }
} 